import { marked } from 'marked';
import hljs from "highlight.js";
import javascript from 'highlight.js/lib/languages/javascript';
import typescript from 'highlight.js/lib/languages/typescript';
import python from 'highlight.js/lib/languages/python';
import java from 'highlight.js/lib/languages/java';
// 导入其他需要的语言...

// 注册语言
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('typescript', typescript);
hljs.registerLanguage('python', python);
hljs.registerLanguage('java', java);
// 注册其他语言...

// 创建 marked 实例
const renderer = new marked.Renderer();

// 重写代码块渲染
renderer.code = function(code, lang) {
    if (!lang) {
        lang = 'markdown'
    }
    try {
        const highlighted = hljs.highlightAuto(code);
        return `
      <div style="position: relative;border-radius: 6px;overflow: hidden;margin: 16px 0;width: 100%" class="code-block">
        <div style="display: flex;justify-content: space-between;align-items: center;padding: 8px 12px;background-color: #f6f8fa;border-bottom: 1px solid #eaecef;font-size: 12px;font-weight: 500; color: #586069;" class="code-header">
          <span style="  background-color: rgba(27, 31, 35, 0.05);padding: 2px 6px;border-radius: 3px;" class="code-language">${lang}</span>
          <button style="border: none;cursor: pointer;color: #586069;padding: 0 8px;display: flex;align-items: center;gap: 4px;" 
                    class="copy-button" data-code="${encodeURIComponent(code)}" title="复制代码">
            复制
          </button>
        </div>
       <pre style="margin: 0 !important; border-radius: 0 10px 0 10px;padding: 10px 16px;" class="hljs-app" ref="messagesCodeRef">
            <code class="hljs">${highlighted.value}</code>
       </pre>
      </div>
    `;
    } catch (err) {
        return `<pre style="margin: 0 !important; border-radius: 0 10px 0 10px;padding: 0 16px;"><code class="hljs">${hljs.highlightAuto(code).value}</code></pre>`;
    }
};

// 配置 marked
const md = marked.setOptions({
    renderer,
    highlight: function(code, lang) {
        // 这里可以添加额外的高亮配置
        if (lang && hljs.getLanguage(lang)) {
            return hljs.highlight(code, { language: lang }).value;
        }
        return hljs.highlightAuto(code).value;
    },
    langPrefix: 'hljs language-', // 为代码块添加语言前缀
    pedantic: false,
    gfm: true,
    breaks: false,
    sanitize: false,
    smartLists: true,
    smartypants: false,
});

export default md;